<template>
  <Dialog
    v-model="show"
    :title="$t('login.找回密码')"
    width="800px"
    :close-on-click-modal="false"
    :hide-footer="true"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="0"
      class="forgetPsw"
    >
      <el-form-item prop="email">
        <el-input
          v-model="formData.email"
          class="form_input"
          :placeholder="$t('login.请输入邮箱')"
        >
          <template #prefix>
            <div class="prefix_label">{{ $t("login.邮箱") }}</div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="emailCode">
        <el-input
          v-model="formData.emailCode"
          class="form_input"
          :placeholder="$t('login.请输入邮箱验证码')"
        >
          <template #prefix>
            <div class="prefix_label">{{ $t("login.邮箱验证码") }}</div>
          </template>
          <template #append>
            <el-button
              :disabled="countdown > 0"
              @click="handleSendCode"
              :loading="sendCodeLoading"
            >
              {{
                countdown > 0
                  ? `${countdown}s`
                  : $t("login.获取验证码")
              }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="formData.password"
          type="password"
          class="form_input"
          :placeholder="$t('login.请设置6~20位字母、数字或符号组成的密码')"
          show-password
        >
          <template #prefix>
            <div class="prefix_label">{{ $t("login.新密码") }}</div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="confirmPassword">
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          class="form_input"
          :placeholder="$t('login.请确认新密码')"
          show-password
        >
          <template #prefix>
            <div class="prefix_label">{{ $t("login.确认密码") }}</div>
          </template>
        </el-input>
      </el-form-item>

      <el-button
        type="primary"
        class="submit_btn"
        @click="handleSubmit"
        :loading="submitLoading"
      >
        {{ $t("user.重置密码") }}
      </el-button>
    </el-form>
  </Dialog>
</template>

<script setup>
import { ref, onUnmounted, watch } from "vue";
import Dialog from "@/components/Dialog.vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import Api from "@/config/api/api";
import Tools from "@/utils/tools";

const { t } = useI18n();
const show = defineModel("show");
const formRef = ref();
const countdown = ref(0);
const sendCodeLoading = ref(false);
const submitLoading = ref(false);
let timer = null;

const formData = ref({
  email: "",
  emailCode: "",
  password: "",
  confirmPassword: "",
});

const validateEmail = (rule, value, callback) => {
  const emaileRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!value) {
    callback(new Error(t("login.请输入邮箱")));
  } else if (!emaileRegex.test(value)) {
    callback(new Error(t("login.请输入正确的邮箱地址")));
  } else {
    callback();
  }
};

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== formData.value.password) {
    callback(new Error(t("login.两次输入的密码不一致")));
  } else {
    callback();
  }
};

const rules = ref({
  email: [{ validator: validateEmail, trigger: "blur" }],
  emailCode: [
    { required: true, message: t("login.请输入邮箱验证码"), trigger: "blur" },
  ],
  password: [
    { required: true, message: t("login.请输入密码"), trigger: "blur" },
    {
      min: 6,
      max: 20,
      message: t("login.密码长度在6-20位之间"),
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z0-9!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]*$/,
      message: t("login.密码只能包含字母、数字或符号"),
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: t("login.请确认密码"), trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
});

const handleSendCode = async () => {
  try {
    const res = await formRef.value.validateField(["email"]);
    if (!res) {
      return;
    }
    sendCodeLoading.value = true;
    Api.forgetPasswordEmailCode({
      email: formData.value.email,
    })
      .then((res) => {
        if (res.status === 200) {
          countdown.value = 60;
          timer = setInterval(() => {
            countdown.value--;
            if (countdown.value <= 0) {
              clearInterval(timer);
            }
          }, 1000);
          ElMessage.success(t("login.验证码发送成功"));
        }
      })
      .finally(() => {
        sendCodeLoading.value = false;
      });
  } catch (error) {
    // ElMessage.error(error.message || t("login.发送验证码失败"));
  }
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    Api.forgetPassword({
      email: formData.value.email,
      emailCode: formData.value.emailCode,
      password: Tools.rsaEncrypt(formData.value.password),
    })
      .then((res) => {
        if (res.status === 200) {
          ElMessage.success(t("login.密码重置成功"));
          show.value = false;
        }
      })
      .finally(() => {
        submitLoading.value = false;
      });
  } catch (error) {
    // console.error("表单验证失败:", error);
  }
};

watch(
  () => show.value,
  (newVal) => {
    if (!newVal) {
      clearInterval(timer);
      countdown.value = 0;
      sendCodeLoading.value = false;
      formData.value = {
        email: "",
        emailCode: "",
        password: "",
      };
    }
  }
);

onUnmounted(() => {
  clearInterval(timer);
});
</script>
<style scoped lang="scss">
.forgetPsw {
  width: 100%;
  padding: 20px;

  .form_input {
    width: 100%;
    height: 40px;

    :deep(.el-input__wrapper) {
      padding-left: 0;
    }
  }

  .prefix_label {
    text-align: center;
    color: #666;
    &::before {
      content: '*';
      color: #FF0000;
    }
  }

  .phone_prefix {
    :deep(.el-select__wrapper) {
      border: none;
      box-shadow: none;
      background-color: rgba(248,248,248,1);
    }
  }

  .code_img {
    height: 40px;
    width: 96px;
  }

  .submit_btn {
    width: 100%;
    height: 40px;
    margin-top: 20px;
  }

  :deep(.el-input__prefix-inner) {
    background-color: rgba(248,248,248,1);
    margin-left: 2px;
    width: 200px;
    display: flex;
    justify-content: end;
    margin-right: 10px;
  }
}
</style>
